package com.copractice.beans.signin;

import java.io.Serializable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.copractice.beans.BaseBean;
import com.copractice.beans.common.Constants;
import com.copractice.beans.common.UserSession;
import com.copractice.bl.BLFactory;
import com.copractice.bl.signin.SignInBL;
import com.copractice.data.entity.user.User;

/**
 * Backing bean for sign in page.
 * 
 * @author Dmitry Churbanov (dmitry.churbanov@gmail.com)
 * @version 1.0 03/14/2009
 */
@SuppressWarnings("serial")
public class SignInBean extends BaseBean implements Serializable {
    
    private static final Logger LOG = LoggerFactory.getLogger(SignInBean.class);
    
    private String username;
    private String password;
    private String errorMessage;
    
    private UserSession session;
    
    public SignInBean() {}
    
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }
    
    public UserSession getSession() {
        return session;
    }

    public void setSession(UserSession session) {
        this.session = session;
    }
    
    public String signInAction() {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Username: '{}'; Passord:'{}';", username, password);
        }
        
        SignInBL siBL = BLFactory.getInstance(SignInBL.class);
        User user = siBL.getValidUser(username, password);
        if (user != null) {
            initializeValues(user);
            
            if (LOG.isDebugEnabled()) {
                LOG.debug("Username: '{}' - user was verified", username);
            }
            return "success";
        } else {
            //TODO: show error message
            //errorMessage = MessagesUtil.getBundleMessage(null, "username_or_password_incorrect");
            
            if (LOG.isDebugEnabled()) {
                LOG.debug("Username: '{}' - verification failed", username);
            }
            return "fail";
        }        
    }
    
    /**
     * Initialize and saves users parameters just after login.
     */
    public void initializeValues(User user) {
        setSessionAttribute(Constants.USER_ID, user.getId());
        setSessionAttribute(Constants.USER_NAME, user.getUserName());
        
        //TODO: Calculate users Knowledge
        //UserKnowledgeBL userKnowledgeBL = new UserKnowledgeBL();
        //userKnowledgeBL.recalculateTeachingScore(user.getId());
    }
    
}
